package cc.cc4414.spring.web.swagger;

import lombok.RequiredArgsConstructor;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpHeaders;
import springfox.documentation.builders.RequestParameterBuilder;
import springfox.documentation.service.*;
import springfox.documentation.spi.DocumentationType;
import springfox.documentation.spi.service.contexts.SecurityContext;
import springfox.documentation.spring.web.plugins.Docket;

import java.util.Collections;
import java.util.List;

/**
 * Swagger的配置
 *
 * @author cc 2019年10月1日
 */
@Configuration
@RequiredArgsConstructor
public class SwaggerConfig {

    private final SwaggerProperties swaggerProperties;

    @Bean
    public Docket api() {
        RequestParameter innerParameter = new RequestParameterBuilder().name("Inner").description("内部请求")
                .in(ParameterType.HEADER).required(false).build();
        return new Docket(DocumentationType.OAS_30).enable(swaggerProperties.isEnabled())
                .globalRequestParameters(Collections.singletonList(innerParameter))
                .securitySchemes(Collections.singletonList(
                        new ApiKey(HttpHeaders.AUTHORIZATION, HttpHeaders.AUTHORIZATION, ParameterType.HEADER.getIn())
                ))
                .securityContexts(Collections.singletonList(
                        SecurityContext.builder().securityReferences(defaultAuth()).build()
                ));
    }

    List<SecurityReference> defaultAuth() {
        return Collections.singletonList(
                SecurityReference.builder()
                        .reference(HttpHeaders.AUTHORIZATION)
                        .scopes(new AuthorizationScope[]{new AuthorizationScope("global", "全局")})
                        .build()
        );
    }
}
